import { ElMessage } from 'element-plus'
import { userStore } from '@/store'

import type { AxiosResponse } from 'axios'

export const failAuth = () => {
  userStore()
    .logout()
    .then(() => {
      location.href = location.origin
    })
}

export const failCodeMap = new Map([
  [400, { msg: '请求错误' }],
  [401, { msg: '未认证', handler: failAuth }],
  [403, { msg: '未授权' }],
  [404, { msg: '请求地址错误' }],
  [405, { msg: '请求方式错误' }],
  [408, { msg: '请求超时' }],
  [422, { msg: '验证错误' }],
  [500, { msg: '服务器内部错误' }],
  [501, { msg: '服务未实现' }],
  [502, { msg: '网关错误' }],
  [503, { msg: '服务不可用' }],
  [504, { msg: '网关超时' }],
  [505, { msg: 'HTTP版本不受支持' }]
])

export const handlerErrorCode = (error: any) => {
  const { status } = error.response

  const { msg, handler }: any = failCodeMap.get(status)
  ElMessage({
    type: 'error',
    message: msg
  })
  if (handler && typeof handler === 'function') handler()
  return Promise.reject(error.response)
}

export const handlerSucessResponse = (response: AxiosResponse) => {
  const { code, msg } = response.data
  // 登录成功
  if (code === 200) {
    return response.data
  }
  ElMessage.error(msg || '系统出错')
  return Promise.reject(new Error(msg || 'Error'))
}
